﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Web7.ExceptionHandling;

namespace Web7.Container.ExceptionPublishers
{
	public class AyncLogExceptionPublisher : IExceptionPublisher
	{

		public AyncLogExceptionPublisher()
		{
			// HACK: 必须为 IExceptionPublisher 写无参构造函数，因为它将由反射调用
		}



		public void Initialize(System.Collections.Specialized.NameValueCollection parameters)
		{

		}

		public void Publish(Exception ex)
		{

			// Must use this ctor to get a FileStream with asynchronous read or write access.
			// TODO: 检查路径
			FileStream fs = new FileStream( String.Empty, FileMode.Append,
				FileAccess.Write, FileShare.None, 4096, true);

			byte[] buffer = Encoding.ASCII.GetBytes(ex.Message);

			// Start the asynchronous write. WriteDone invoked when finished.
			// Note that the FileStream object is passed as state info to the callback method.
			fs.BeginWrite(buffer, 0, buffer.Length, new AsyncCallback(WriteDone), fs);
		}

		private static void WriteDone(IAsyncResult ar)
		{
			// TODO: 对多线程的支持[回调时，如果缓冲区仍有数据未写入，继续写入]
			Stream s = (Stream)ar.AsyncState;
			s.EndWrite(ar);
			s.Close();
		}


	}
}
